package wang.conge.javasedemo.core.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author conge
 * 2016年7月14日
 */
public class BlockingIOClient implements Runnable{
	private String name;
	private String ip;
	private int port;
	
	public BlockingIOClient(String index,String ip,int port){
		this.name  = index;
		this.ip = ip;
		this.port = port;
	}
	
	@Override
	public void run() {
		Socket socket =  null;
		try {
			socket = new Socket(ip, port);
			
			String req = "req:" + name + ",END";
			
			socket.getOutputStream().write(req.getBytes());
			socket.getOutputStream().flush();
			
			InputStream input = socket.getInputStream();
			
			StringBuilder sb = new StringBuilder();
			byte[] bytes = new byte[1024];
			while(true){
				int read = input.read(bytes);
				if(read<0){
					break;
				}
				
				String res = new String(bytes);
				res = res.trim();
				sb.append(res);
				if(res.endsWith("END")){
					break;
				}
			}
			//TODO service
			System.out.println(sb);
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(!socket.isClosed()){
				try {
					socket.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	public static void main(String[] args) {
		String ip = "127.0.0.1";
		int port = 10000;
		
		for(int i=0;i<10;i++){
			String name = "client:"+i;
			
			new Thread(new BlockingIOClient(name,ip,port)).start();
		}
		
	}
	
}
